package cn.butcher21.dao;

import cn.butcher21.pojo.Sale;
import cn.butcher21.pojo.SaleData;
import cn.butcher21.utils.DBUtil;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * butcher create in 2021/05/05/15:32
 */
public class SaleDao {
    public void add(List<Sale> sales) throws SQLException, IOException, ClassNotFoundException {
        DBUtil dbUtil = new DBUtil();
        String sql = "INSERT INTO T_SALE(S_ID, G_ID, S_COUNT, U_NAME) VALUES (?,?,?,?)";
        PreparedStatement ps = dbUtil.getPs(sql);
        for (Sale sale : sales) {
            ps.setString(1, sale.getSid());
            ps.setString(2, sale.getGid());
            ps.setInt(3, sale.getCount());
            ps.setString(4, sale.getSaleMan());
            ps.execute();
        }

    }

    public SaleData getSale(String id) throws SQLException, IOException, ClassNotFoundException {
        DBUtil dbUtil = new DBUtil();
        SaleData sale = new SaleData();
        String sql = "SELECT G_ID, G_NAME, G_PRICE FROM T_GOODS WHERE G_ID=?";
        PreparedStatement ps = dbUtil.getPs(sql);
        ps.setString(1, id);
        ResultSet rs = dbUtil.getRs(ps.executeQuery());
        if (rs.next()) {
            sale.setId(rs.getString(1));
            sale.setName(rs.getString(2));
            sale.setPrice(rs.getDouble(3));
        }
        return sale;
    }

    public boolean check(String id) {
        try {
            DBUtil dbUtil = new DBUtil();
            String sql = "SELECT G_COUNT FROM t_goods where G_ID=?";
            PreparedStatement ps = dbUtil.getPs(sql);
            ps.setString(1, id);
            ResultSet rs = dbUtil.getRs(ps.executeQuery());
            if (rs.next()) {
                if (rs.getInt(1) > 0) {
                    return true;
                }
            }
            dbUtil.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public void reduce(String id, int count) {
        try {
            DBUtil dbUtil = new DBUtil();
            String sql = "UPDATE t_goods SET g_count = g_count-? where G_ID =? ";
            PreparedStatement ps = dbUtil.getPs(sql);
            ps.setString(2, id);
            ps.setInt(1, count);
            ps.executeUpdate();
            dbUtil.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
